package com.jeeplus.modules.api;


import com.alibaba.fastjson.JSONObject;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.IdGen;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.config.properties.JeePlusProperites;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.activity.entity.Activity;
import com.jeeplus.modules.activity.service.ActivityService;
import com.jeeplus.modules.agreement.entity.Agreement;
import com.jeeplus.modules.agreement.service.AgreementService;
import com.jeeplus.modules.api.common.UUIDUtils;
import com.jeeplus.modules.api.enums.OrderStateEnum;
import com.jeeplus.modules.api.req.ReqJson;
import com.jeeplus.modules.api.utils.*;
import com.jeeplus.modules.api.wxpay.WxPayUtils;
import com.jeeplus.modules.banner.entity.Banner;
import com.jeeplus.modules.banner.service.BannerService;
import com.jeeplus.modules.customerservice.entity.CustomerService;
import com.jeeplus.modules.customerservice.service.CustomerServiceService;
import com.jeeplus.modules.member.entity.Member;
import com.jeeplus.modules.member.service.MemberService;
import com.jeeplus.modules.redeemcode.entity.RedeemCode;
import com.jeeplus.modules.redeemcode.service.RedeemCodeService;
import com.jeeplus.modules.redeemmanager.entity.RedeemManager;
import com.jeeplus.modules.redeemmanager.service.RedeemManagerService;
import com.jeeplus.modules.tickettype.entity.TicketType;
import com.jeeplus.modules.tickettype.service.TicketTypeService;
import com.jeeplus.modules.topic.entity.Topic;
import com.jeeplus.modules.topic.entity.TopicTicket;
import com.jeeplus.modules.topic.mapper.TopicTicketMapper;
import com.jeeplus.modules.topic.service.TopicService;
import com.jeeplus.modules.userorder.entity.UserOrder;
import com.jeeplus.modules.userorder.service.UserOrderService;
import com.jeeplus.modules.video.entity.Video;
import com.jeeplus.modules.video.service.VideoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/user/")
@Slf4j
public class MicroAppController extends BaseController {

    private final AgreementService agreementService;
    private final RedisTemplate<String, String> redisTemplate;
    private final MemberService memberService;
    private final BannerService bannerService;
    private final VideoService videoService;
    private final TopicService topicService;
    private final RedeemManagerService redeemManagerService;
    private final RedeemCodeService redeemCodeService;
    private final TicketTypeService ticketTypeService;
    private final TopicTicketMapper topicTicketMapper;
    private final UserOrderService userOrderService;
    private final CustomerServiceService customerServiceService;
    private final ActivityService activityService;

    public MicroAppController(AgreementService agreementService, RedisTemplate<String, String> redisTemplate, MemberService memberService, BannerService bannerService, VideoService videoService, TopicService topicService, RedeemManagerService redeemManagerService, RedeemCodeService redeemCodeService, TicketTypeService ticketTypeService, TopicTicketMapper topicTicketMapper, UserOrderService userOrderService, CustomerServiceService customerServiceService, ActivityService activityService) {
        this.agreementService = agreementService;
        this.redisTemplate = redisTemplate;
        this.memberService = memberService;
        this.bannerService = bannerService;
        this.videoService = videoService;
        this.topicService = topicService;
        this.redeemManagerService = redeemManagerService;
        this.redeemCodeService = redeemCodeService;
        this.ticketTypeService = ticketTypeService;
        this.topicTicketMapper = topicTicketMapper;
        this.userOrderService = userOrderService;
        this.customerServiceService = customerServiceService;
        this.activityService = activityService;
    }

    /**
     * 上传单张图片返回链接
     *
     * @return ajaxJson
     */
    @RequestMapping("uploadFile")
    public AjaxJson addImages(@RequestParam(value = "file", required = false) MultipartFile[] file) {
        AjaxJson res = new AjaxJson();
        res.setMsg("上传失败");
        try {
            List<String> list = new ArrayList<>();
            if (file != null && file.length > 0) {
                for (MultipartFile multipartFile : file) {
                    String realPath = JeePlusProperites.newInstance().getUserfilesBaseDir() + "userfiles/1/files/authimage";
                    // String dateDir = DateTimeUtil.dateConvtoFmt(new Date(),
                    // "yyyyMM"); // 按日期存放上传的文件
                    String[] split = DateUtils.formatDate(new Date(), "yyyy-MM").split("-");
                    String dateDir = split[0] + "/" + split[1];
                    File path = new File(realPath + File.separator + dateDir);
                    if (!path.exists()) {
                        path.mkdirs();
                    }
                    String filename1 = multipartFile.getOriginalFilename();
                    String ext1 = null;
                    if (filename1 != null) {
                        ext1 = filename1.substring(filename1.lastIndexOf(".")).toLowerCase();
                    }
                    String fileName1 = DateUtils.formatDate(new Date(), "yyyyMMddHHmmss")
                            + RandomStringUtils.randomNumeric(4) + ext1;
                    File localFile1 = new File(path.getAbsolutePath() + File.separator + fileName1);
                    multipartFile.transferTo(localFile1);
                    list.add(filePath + "/userfiles/1/files/authimage/" + dateDir + "/" + fileName1);
                }
            }
            res.put("dataList", list);
            res.setCode(0);
            res.setMsg("提交成功");
        } catch (Exception e) {
            log.error("请求失败:{}", e);
        }
        return res;
    }

    /**
     * 各种协议
     *
     * @param req 类型
     * @return 协议信息
     */
    @RequestMapping("getAgreement")
    public AjaxJson agreement(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String type = req.getString("type");
        if (StringUtils.isBlank(type)) {
            ajaxJson.setMsg("类型不能为空");
            return ajaxJson;
        }
        Agreement type1 = agreementService.findUniqueByProperty("type", type);
        if (Objects.isNull(type1)) {
            ajaxJson.setMsg("信息不存在");
            return ajaxJson;
        }
        ajaxJson.put("data", type1.getContent());
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * 请求验证码
     *
     * @param req 手机号
     * @return 验证码
     */
    @RequestMapping("requestMsg")
    public AjaxJson requestMsg(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String mobile = req.getString("mobile");
        if (StringUtils.isBlank(mobile)) {
            ajaxJson.setMsg("手机号不能为空");
            return ajaxJson;
        }
        // 生成6位验证码
        String uuid = UUIDUtils.uuid(6);
        logger.info("验证码:{}", uuid);
        // 发送验证码
        String[] mobiles = {mobile};
        String[] codes = {uuid};
        TenSms.sendSms(mobiles, codes);
        // 将验证码有效期设置为5分钟
        redisTemplate.opsForValue().set(mobile, uuid, 5, TimeUnit.MINUTES);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * 手机号登录
     *
     * @param req 参数
     * @return 状态
     */
    @RequestMapping("loginByPhone")
    public AjaxJson loginByPhone(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String mobile = req.getString("mobile");
        String referralCode = req.getString("referralCode");
        String code = req.getString("code");
        if (StringUtils.isBlank(mobile)) {
            ajaxJson.setMsg("手机号不能为空");
            return ajaxJson;
        }
        if (StringUtils.isBlank(code)) {
            ajaxJson.setMsg("验证码不能为空");
            return ajaxJson;
        }
        String s = redisTemplate.opsForValue().get(mobile);
        if (StringUtils.isBlank(s) || !s.equals(code)) {
            ajaxJson.setMsg("手机号或验证码错误");
            return ajaxJson;
        }
        Member user = memberService.findUniqueByProperty("mobile", mobile);
        Map<String, Object> map = new HashMap<>();
        if (Objects.isNull(user)) {
            Member member = new Member();
            member.setMobile(mobile);
            member.setEarning("0.00");
            member.setInviteCode(IdGen.uuid().substring(10));
            member.setRadio("0");
            member.setBalance("0.00");
            member.setUserType("1");
            member.setNickname("用户" + mobile.substring(7));
            if (StringUtils.isNotBlank(referralCode)) {
                // 通过推荐码查询推荐人
                Member invite = memberService.findUniqueByProperty("invite_code", referralCode);
                if (!Objects.isNull(invite)) {
                    // 设置推荐人
                    member.setInvite(invite);
                }
            }
            memberService.save(member);
            map.put("uid", member.getId());
            map.put("userType", "1");
            map.put("mobile", member.getMobile());
        } else {
            map.put("uid", user.getId());
            map.put("userType", user.getUserType());
            map.put("mobile", user.getMobile());
        }
        ajaxJson.put("data", map);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("登录成功");
        return ajaxJson;
    }

    /**
     * 微信授权登录
     *
     * @param req 参数
     * @return 状态
     */
    @RequestMapping("loginByWechat")
    public AjaxJson loginByWechat(@RequestBody ReqJson req) throws Exception {
        AjaxJson ajaxJson = new AjaxJson();
        String openCode = req.getString("openCode");
        String referralCode = req.getString("referralCode");
        JSONObject userInfo = req.getJSONObject("userInfo");
        String encryptedData = req.getString("encryptedData");
        String phoneCode = req.getString("phoneCode");
        String iv = req.getString("iv");
        if (StringUtils.isBlank(openCode)) {
            ajaxJson.setMsg("code不能为空");
            return ajaxJson;
        }
        if (Objects.isNull(userInfo)) {
            ajaxJson.setMsg("用户信息不能为空！");
            return ajaxJson;
        }
        if (StringUtils.isBlank(encryptedData) || StringUtils.isBlank(iv)) {
            ajaxJson.setMsg("手机号获取参数不能为空！");
            return ajaxJson;
        }
        Map<String, Object> map = new HashMap<>();
        // 获取用户手机号判断该用户是否注册
        String encryptedData1 = URLDecoder.decode(encryptedData, "UTF-8").replace(" ", "+");
        String iv1 = URLDecoder.decode(iv, "UTF-8").replace(" ", "+");
        String requestUrl = ApiUserUtils.getWebAccess(phoneCode, appId, appSecret);// 通过自定义工具类组合出小程序需要的登录凭证
        JSONObject sessionData = CommonUtil.httpsRequest(requestUrl, "GET", null);
        String session_key = URLDecoder.decode(sessionData.getString("session_key"), "UTF-8").replace(" ", "+");
        // 被加密的数据
        byte[] dataByte = org.apache.commons.codec.binary.Base64.decodeBase64(encryptedData1);
        // 加密秘钥
        byte[] keyByte = org.apache.commons.codec.binary.Base64.decodeBase64(session_key);
        // 偏移量
        byte[] ivByte = Base64.decodeBase64(iv1);
        byte[] resultByte = AESUtil.instance.decrypt(dataByte, keyByte, ivByte);
        if (null != resultByte && resultByte.length > 0) {
            String result = new String(resultByte, StandardCharsets.UTF_8);
            JSONObject parse = JSONObject.parseObject(result);
            String mobile = parse.getString("phoneNumber");
            if (StringUtils.isNotBlank(mobile)) {
                // 获取用户的openid
                Member user = memberService.findUniqueByProperty("mobile", mobile);
                String request = ApiUserUtils.getWebAccess(openCode, appId, appSecret);// 通过自定义工具类组合出小程序需要的登录凭证
                logger.info("》》》组合token为：" + request);
                JSONObject session = CommonUtil.httpsRequest(request, "GET", null);
                if (Objects.isNull(user)) {
                    if (Objects.isNull(session) || StringUtils.isBlank(session.getString("openid"))) {
                        ajaxJson.setMsg("登录失败");
                        return ajaxJson;
                    }
                    Member member = new Member();
                    member.setNickname(req.getJSONObject("userInfo").getString("nickName"));
                    member.setPhoto(req.getJSONObject("userInfo").getString("avatarUrl"));
                    member.setOpenid(session.getString("openid"));
                    member.setEarning("0.00");
                    member.setInviteCode(IdGen.uuid().substring(0, 10));
                    member.setRadio("0");
                    member.setBalance("0.00");
                    member.setUserType("1");
                    member.setMobile(mobile);
                    if ("1".equals(req.getJSONObject("userInfo").getString("gender"))) {// 性别
                        // 0：未知、1：男、2：女
                        member.setGender("1");
                    } else if ("2".equals(req.getJSONObject("userInfo").getString("gender"))) {
                        member.setGender("2");
                    } else {
                        member.setGender("0");
                    }
                    // 添加推荐码
                    if (StringUtils.isNotBlank(referralCode)) {
                        // 通过推荐码查询推荐人
                        Member invite = memberService.findUniqueByProperty("invite_code", referralCode);
                        if (!Objects.isNull(invite)) {
                            // 设置推荐人
                            member.setInvite(invite);
                        }
                    }
                    memberService.save(member);
                    map.put("uid", member.getId());
                    map.put("userType", "1");
                    map.put("mobile", mobile);
                } else {
                    // 如果用户存在判断该用户的openid是否存在
//                    Member open = memberService.findUniqueByProperty("openid", user.getOpenid());
//                    if (Objects.isNull(open)) {
                    user.setNickname(req.getJSONObject("userInfo").getString("nickName"));
                    user.setPhoto(req.getJSONObject("userInfo").getString("avatarUrl"));
                    user.setOpenid(session.getString("openid"));
                    if ("1".equals(req.getJSONObject("userInfo").getString("gender"))) {// 性别
                        // 0：未知、1：男、2：女
                        user.setGender("1");
                    } else if ("2".equals(req.getJSONObject("userInfo").getString("gender"))) {
                        user.setGender("2");
                    } else {
                        user.setGender("0");
                    }
                    memberService.save(user);
//                    }
                    map.put("uid", user.getId());
                    map.put("userType", user.getUserType());
                    map.put("mobile", user.getMobile());
                }
                ajaxJson.setCode(0);
                ajaxJson.setMsg("登录成功");
                ajaxJson.put("data", map);
            }
        } else {
            ajaxJson.setMsg("手机号获取失败");
        }
        return ajaxJson;
    }


    /**
     * 首页
     *
     * @return 状态
     */
    @RequestMapping("index")
    public AjaxJson index(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        Integer pageNo = req.getInteger("pageNo");
        Integer pageSize = req.getInteger("pageSize");
        Map<String, Object> maps = new HashMap<>();
        // 轮播图查询
        List<Banner> bannerList = bannerService.findList(new Banner());
        List<Map<String, Object>> mapListBanner = new ArrayList<>();
        for (Banner banner : bannerList) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", banner.getId());
            map.put("image", getRealPath(banner.getImage()));
            mapListBanner.add(map);
        }
        // 主题查询
        List<Topic> topicList = topicService.findList(new Topic());
        List<Map<String, Object>> mapListTopic = new ArrayList<>();
        for (Topic topic : topicList) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", topic.getId());
            map.put("title", topic.getTitle());
            map.put("notes", topic.getNotes());
            map.put("icon", getRealPath(topic.getIcon()));
            map.put("address", topic.getAddress());
            map.put("addressDetail", topic.getAddressDetail());
            map.put("salesType", topic.getSalesState());
            map.put("minPrice", topic.getMinPrice());
            map.put("maxPrice", topic.getMaxPrice());
            mapListTopic.add(map);
        }
        // 兑换开关查询
        List<RedeemManager> list = redeemManagerService.findList(new RedeemManager());
        RedeemManager redeemManager = list.get(0);
        Map<String, Object> mapRedeemManager = new HashMap<>();
        mapRedeemManager.put("image", getRealPath(redeemManager.getImage()));
        mapRedeemManager.put("openState", redeemManager.getOpenState());
        // 视频查询
        Page<Video> page = videoService.findPage(new Page<>(pageNo, pageSize), new Video());
        List<Map<String, Object>> mapListVideo = new ArrayList<>();
        page.getList().sort(Comparator.comparing(Video::getSort));
        for (Video video : page.getList()) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", video.getId());
            map.put("image", getRealPath(video.getImage()));
            map.put("title", video.getTitle());
            mapListVideo.add(map);
        }
        maps.put("total", page.getLast());
        maps.put("count", page.getCount());
        maps.put("bannerList", mapListBanner);
        maps.put("topicList", mapListTopic);
        maps.put("redeemManager", mapRedeemManager);
        maps.put("videoList", mapListVideo);
        ajaxJson.put("data", maps);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * 轮播图详情
     *
     * @param req 参数
     * @return 状态
     */
    @RequestMapping("bannerInfo")
    public AjaxJson bannerInfo(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String bannerId = req.getString("bannerId");
        if (StringUtils.isBlank(bannerId)) {
            ajaxJson.setMsg("轮播图id不能为空");
            return ajaxJson;
        }
        Banner banner = bannerService.get(bannerId);
        if (Objects.isNull(banner)) {
            ajaxJson.setMsg("轮播图不存在");
            return ajaxJson;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("title", banner.getTitle());
        map.put("image", getRealPath(banner.getImage()));
        map.put("content", banner.getContent());
        map.put("url", banner.getUrl());
        ajaxJson.put("data", map);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("加载成功");
        return ajaxJson;
    }

    /**
     * 视频详情
     *
     * @param req 参数
     * @return 状态
     */
    @RequestMapping("videoInfo")
    public AjaxJson videoInfo(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String videoId = req.getString("videoId");
        if (StringUtils.isBlank(videoId)) {
            ajaxJson.setMsg("视频id不能为空");
            return ajaxJson;
        }
        Video video = videoService.get(videoId);
        if (Objects.isNull(video)) {
            ajaxJson.setMsg("该视频不存在");
            return ajaxJson;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("id", video.getId());
        map.put("title", video.getTitle());
        map.put("url", video.getUrl());
        ajaxJson.put("data", map);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * 主题详情
     *
     * @param req 参数
     * @return 状态
     */
    @RequestMapping("topicInfo")
    public AjaxJson topicInfo(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String topicId = req.getString("topicId");
        if (StringUtils.isBlank(topicId)) {
            ajaxJson.setMsg("主题id不能为空");
            return ajaxJson;
        }
        Topic topic = topicService.get(topicId);
        if (Objects.isNull(topic)) {
            ajaxJson.setMsg("该主题不存在");
            return ajaxJson;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("id", topic.getId());
        map.put("title", topic.getTitle());
        map.put("image", getRealPath(topic.getImage()));
        map.put("icon", getRealPath(topic.getIcon()));
        map.put("minPrice", topic.getMinPrice());
        map.put("maxPrice", topic.getMaxPrice());
        map.put("address", topic.getAddress());
        map.put("addressDetail", topic.getAddressDetail());
        map.put("saleState", topic.getSalesState());
        map.put("presellEndDate", Objects.isNull(topic.getPresellEndDate()) ? "" : topic.getPresellEndDate());
        map.put("useDate", topic.getUseDate());
        map.put("content", topic.getContent());
        map.put("virtualSaleValue", topic.getVirtualSalesValue());
        map.put("qrImage", getRealPath(topic.getQrImage()));
        map.put("linkman", topic.getLinkman());
        map.put("lon", StringUtils.isBlank(topic.getLon()) ? "" : topic.getLon());
        map.put("lat", StringUtils.isBlank(topic.getLat()) ? "" : topic.getLat());
        map.put("wechat", topic.getWechat());
        map.put("serviceMobile", topic.getServiceMobile());
        ajaxJson.put("data", map);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * 兑换码领票
     *
     * @param req 参数
     * @return 状态
     */
    @RequestMapping("redeemTicket")
    public AjaxJson redeemTicket(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
//        String uid = req.getString("uid");
        String redeemCode = req.getString("redeemCode");
//        if (StringUtils.isBlank(uid)) {
//            ajaxJson.setMsg("用户id不能为空");
//            return ajaxJson;
//        }
        if (StringUtils.isBlank(redeemCode)) {
            ajaxJson.setMsg("兑换码不能为空");
            return ajaxJson;
        }
//        Member member = memberService.get(uid);
//        if (Objects.isNull(member)) {
//            ajaxJson.setMsg("该用户不存在");
//            return ajaxJson;
//        }
        // 查询兑换码有效性
        RedeemCode code = redeemCodeService.findUniqueByProperty("code", redeemCode);
        if (Objects.isNull(code)) {
            ajaxJson.setMsg("该兑换码不存在");
            return ajaxJson;
        }
        if (code.getRedeemState().equals("1")) {
            ajaxJson.setMsg("该兑换码已失效");
            return ajaxJson;
        }
        // 查询主题信息
        RedeemCode redeemCode1 = redeemCodeService.get(code);
        Topic topic = topicService.get(redeemCode1.getTopic());
        if (Objects.isNull(topic)) {
            ajaxJson.setMsg("未查到相关主题信息");
            return ajaxJson;
        }
        // 查询购票须知
        Agreement agreement = agreementService.findUniqueByProperty("type", "3");
        // 查新兑换码门票类型
        TicketType ticketType = ticketTypeService.get(code.getTicketTypeId());
        // 获取开场时间
        List<Map<String, Object>> mapList = topicTicketMapper.execSelectSql("select start_time as startTime, end_time as endTime from t_topic_ticket where topic_id = '" + topic.getId() + "' and ticket_type_id = '" + code.getTicketTypeId() + "'");
        // 通过兑换码查询门票信息
        Map<String, Object> map = new HashMap<>();
        map.put("topicId", topic.getId());
        map.put("ticketTypeId", code.getTicketTypeId());
        map.put("title", topic.getTitle());
        map.put("ticketType", StringUtils.isBlank(ticketType.getTitle()) ? "" : ticketType.getTitle());
        map.put("startDate", mapList.get(0).get("startTime"));
        map.put("endDate", mapList.get(0).get("endTime"));
        map.put("quantity", redeemCode1.getQuantity());
//        map.put("mobile", member.getMobile());
        map.put("ticketNotes", agreement.getContent());
        map.put("redeemCode", redeemCode);
        ajaxJson.put("data", map);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * 兑票
     *
     * @param req 参数
     * @return 状态
     */
    @RequestMapping("openTicket")
    public AjaxJson openTicket(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String uid = req.getString("uid");
        String useDate = req.getString("useDate");
        Integer quantity = req.getInteger("quantity");
        String redeemCode = req.getString("redeemCode");
        String mobile = req.getString("mobile");
        String topicTitle = req.getString("topicTitle");
        String ticketType = req.getString("ticketType");
        String ticketTypeId = req.getString("ticketTypeId");
        String startTime = req.getString("startTime");
        String endTime = req.getString("endTime");
        String topicId = req.getString("topicId");
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        if (Objects.isNull(quantity)) {
            ajaxJson.setMsg("数量不能为空");
            return ajaxJson;
        }
        if (StringUtils.isBlank(useDate)) {
            ajaxJson.setMsg("使用时间不能为空");
            return ajaxJson;
        }
        if (StringUtils.isBlank(redeemCode)) {
            ajaxJson.setMsg("兑换码不能为空");
            return ajaxJson;
        }
        if (StringUtils.isBlank(mobile)) {
            ajaxJson.setMsg("手机号不能为空");
            return ajaxJson;
        }
        if (StringUtils.isBlank(topicTitle)) {
            ajaxJson.setMsg("主题名称不能为空");
            return ajaxJson;
        }
        if (StringUtils.isBlank(ticketType)) {
            ajaxJson.setMsg("门票类型不能为空");
            return ajaxJson;
        }
        if (StringUtils.isBlank(startTime) || StringUtils.isBlank(endTime)) {
            ajaxJson.setMsg("门票类型不能为空");
            return ajaxJson;
        }
        if (StringUtils.isBlank(topicId)) {
            ajaxJson.setMsg("主题id不能为空");
            return ajaxJson;
        }
        Topic topic = topicService.get(topicId);
        if (Objects.isNull(topic)) {
            ajaxJson.setMsg("该主题不存在");
            return ajaxJson;
        }
        // 修改兑换码状态
        RedeemCode code = redeemCodeService.findUniqueByProperty("code", redeemCode);
        code.setTopic(topic);
        // 添加订单信息
        UserOrder userOrder = new UserOrder();
        userOrder.setIsNewRecord(true);
        userOrder.setId(UUIDUtils.orderUuid(6));
        userOrder.setU(member);
        userOrder.setPayAmount("0.00");
        userOrder.setIncome("0.00");
        userOrder.setBrokerage("0.00");
        userOrder.setUseDate(useDate);
        userOrder.setQuantity(quantity);
        userOrder.setAddress(topic.getAddress());
        userOrder.setAddressDetail(topic.getAddressDetail());
        userOrder.setAuthCode(IdGen.uuid().substring(0, 8));
        userOrder.setMobile(mobile);
        userOrder.setTicketType(ticketType);
        userOrder.setTicketTypeId(ticketTypeId);
        userOrder.setTopicTitle(topicTitle);
        userOrder.setTopic(topic);
        userOrder.setStartTime(startTime);
        userOrder.setEndTime(endTime);
        userOrder.setOrderState(OrderStateEnum.WAIT_USE.getCode());
        userOrder.setPayDate(new Date());
        userOrder.setOrderType("2");
        userOrder.setShopTitle(topic.getShopTitle());
        userOrderService.redeemOrder(userOrder, code, topic);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("兑换成功");
        return ajaxJson;
    }


    /**
     * 购票
     *
     * @param req 参数
     * @return 状态
     */
    @RequestMapping("buyTicket")
    public AjaxJson buyTicket(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String topicId = req.getString("topicId");
        String uid = req.getString("uid");
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        if (StringUtils.isBlank(topicId)) {
            ajaxJson.setMsg("主题id不能为空");
            return ajaxJson;
        }
        Topic topic = topicService.get(topicId);
        if (Objects.isNull(topic)) {
            ajaxJson.setMsg("该主题不存在");
            return ajaxJson;
        }
        // 查询购票须知
        Agreement agreement = agreementService.findUniqueByProperty("type", "3");
        // 查询该主题下的门票类型
        TopicTicket topicTicket = new TopicTicket();
        topicTicket.setTopic(topic);
        List<TopicTicket> list = topicTicketMapper.findList(topicTicket);
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (TopicTicket ticket : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", ticket.getTicketType().getId());
            map.put("ticketType", ticket.getTicketType().getTitle());
            map.put("price", ticket.getPrice());
            map.put("startTime", ticket.getStartTime());
            map.put("endTime", ticket.getEndTime());
            // 查询当日的单量
            UserOrder userOrder = new UserOrder();
            userOrder.setTicketTypeId(ticket.getTicketType().getId());
            userOrder.setTopic(topic);
            userOrder.setDataScope(" and DATE_FORMAT(a.create_date, '%Y-%m-%d') = '" + ymd(new Date()) + "'");
            List<UserOrder> list3 = userOrderService.findList(userOrder);
            map.put("stock", ticket.getStock() - list3.size());
            //
            map.put("isAct", "0");
//            Activity act = new Activity();
//            act.setTopic(topic);
//            act.setTicketTypeId(ticket.getTicketType().getId());
//            act.setDataScope(" and a.act_date >= '" + ymd(new Date()) + "'");
//            List<Activity> list2 = activityService.findList(act);
//            if (CollectionUtils.isNotEmpty(list2)) {
//                Activity activity = list2.get(0);
//                map.put("price", activity.getPrice());
//                map.put("stock", activity.getQuantity() - list3.size());
//                map.put("isAct", "1");
//            }
            mapList.add(map);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("id", topic.getId());
        map.put("title", topic.getTitle());
        map.put("presellStartDate", Objects.isNull(topic.getPresellStartDate()) ? "" : topic.getPresellStartDate());
        map.put("presellEndDate", Objects.isNull(topic.getPresellEndDate()) ? "" : topic.getPresellEndDate());
        map.put("mobile", member.getMobile());
        map.put("ticketNotes", agreement.getContent());
        map.put("salesState", topic.getSalesState());
        map.put("topicTypeList", mapList);
        ajaxJson.put("data", map);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * 创建订单
     *
     * @param req 参数
     * @return 状态
     */
    @RequestMapping("createOrder")
    public synchronized AjaxJson createOrder(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String uid = req.getString("uid");
        String topicId = req.getString("topicId");
        String useDate = req.getString("useDate");
        String payAmount = req.getString("payAmount");
        Integer quantity = req.getInteger("quantity");
        String ticketTypeId = req.getString("ticketTypeId");
        String mobile = req.getString("mobile");
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        if (StringUtils.isBlank(topicId)) {
            ajaxJson.setMsg("主题id不能为空");
            return ajaxJson;
        }
        Topic topic = topicService.get(topicId);
        if (Objects.isNull(topic)) {
            ajaxJson.setMsg("该主题不存在");
            return ajaxJson;
        }
        if (StringUtils.isBlank(useDate)) {
            ajaxJson.setMsg("使用时间不能为空");
            return ajaxJson;
        }
        if (StringUtils.isBlank(payAmount)) {
            ajaxJson.setMsg("订单金额不能为空");
            return ajaxJson;
        }
        if (Objects.isNull(quantity)) {
            ajaxJson.setMsg("数量不能为空");
            return ajaxJson;
        }
        if (StringUtils.isBlank(ticketTypeId)) {
            ajaxJson.setMsg("门票类型id不能为空");
            return ajaxJson;
        }
        if (StringUtils.isBlank(mobile)) {
            ajaxJson.setMsg("用户手机号不能为空");
            return ajaxJson;
        }
        // 查询该票是否存在活动
        Activity activity = new Activity();
        activity.setTopic(topic);
        activity.setActDate(useDate);
        activity.setTicketTypeId(ticketTypeId);
        List<Activity> list = activityService.findList(activity);
        if (CollectionUtils.isNotEmpty(list)) {
            Activity activity1 = list.get(0);
            // 确认库存
            if (activity1.getSurplus() == 0) {
                ajaxJson.setMsg("库存不足");
                return ajaxJson;
            }
        } else {
            TopicTicket topicTicket = new TopicTicket();
            topicTicket.setTopic(topic);
            topicTicket.setTicketType(new TicketType(ticketTypeId));
            List<TopicTicket> list1 = topicTicketMapper.findList(topicTicket);
            if (CollectionUtils.isNotEmpty(list1)) {
                // 比较下单日期
                TopicTicket topicTicket1 = list1.get(0);
                UserOrder userOrder = new UserOrder();
                userOrder.setUseDate(useDate);
                userOrder.setTopic(topic);
                userOrder.setTicketTypeId(ticketTypeId);
                List<UserOrder> list2 = userOrderService.findList(userOrder);
                int orderSurplus = topicTicket1.getStock() - list2.size();
                if (orderSurplus == 0) {
                    ajaxJson.setMsg("库存不足");
                    return ajaxJson;
                }
            }
        }
        TicketType ticketType = ticketTypeService.get(ticketTypeId);
        // 查询主题门票的信息
        List<Map<String, Object>> mapList = topicTicketMapper.execSelectSql("select start_time as startTime, end_time as endTime, id from t_topic_ticket where topic_id = '" + topic.getId() + "' and ticket_type_id = '" + ticketTypeId + "'");
        TopicTicket topicTicket1 = topicTicketMapper.get(mapList.get(0).get("id").toString());
        UserOrder userOrder = new UserOrder();
        userOrder.setIsNewRecord(true);
        userOrder.setId(UUIDUtils.orderUuid(6));
        userOrder.setU(member);
        userOrder.setUseDate(useDate);
        userOrder.setPayAmount(payAmount);
        userOrder.setQuantity(quantity);
        userOrder.setAddress(topic.getAddress());
        userOrder.setAddressDetail(topic.getAddressDetail());
        userOrder.setTopic(topic);
        userOrder.setTicketTypeId(ticketTypeId);
        userOrder.setTopicTitle(topic.getTitle());
        userOrder.setTicketType(ticketType.getTitle());
        userOrder.setMobile(mobile);
        userOrder.setStartTime(mapList.get(0).get("startTime").toString());
        userOrder.setEndTime(mapList.get(0).get("endTime").toString());
        userOrder.setAuthCode(UUIDUtils.uuid(8));
        userOrder.setOrderState(OrderStateEnum.WAIT_PAY.getCode());
        userOrder.setPayState("0");
        userOrder.setOrderType("1");
        userOrder.setShopTitle(topic.getShopTitle());
        userOrderService.createOrder(userOrder, topicTicket1);
        Map<String, Object> map = new HashMap<>();
        map.put("orderId", userOrder.getId());
        map.put("address", userOrder.getAddress() + userOrder.getAddressDetail());
        ajaxJson.put("data", map);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * 订单列表
     *
     * @param req 参数
     * @return 状态
     */
    @RequestMapping("orderList")
    public AjaxJson orderList(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String uid = req.getString("uid");
        String orderState = req.getString("orderState");
        Integer pageNo = req.getInteger("pageNo");
        Integer pageSize = req.getInteger("pageSize");
        if (StringUtils.isBlank(orderState)) {
            ajaxJson.setMsg("订单状态不能为空");
            return ajaxJson;
        }
        if (Objects.isNull(pageNo) || Objects.isNull(pageSize)) {
            ajaxJson.setMsg("分页参数不能为空");
            return ajaxJson;
        }
        UserOrder userOrder = new UserOrder();
        switch (orderState) {
            case "3":
                userOrder.setDataScope(" and a.order_state in ('3')");
                break;
            case "2":
                userOrder.setDataScope(" and a.order_state in ('2')");
                break;
            case "1":
                userOrder.setDataScope(" and a.order_state in ('1')");
                break;
            default:
                userOrder.setDataScope(" and a.order_state in ('1', '2', '3', '4', '6')");
                break;
        }
        userOrder.setU(new Member(uid));
        Page<UserOrder> page = userOrderService.findPage(new Page<>(pageNo, pageSize), userOrder);
        Map<String, Object> maps = new HashMap<>();
        maps.put("total", page.getLast());
        maps.put("count", page.getCount());
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (UserOrder order : page.getList()) {
            Map<String, Object> map = new HashMap<>();
            // 查询主题信息
            Topic topic = topicService.get(order.getTopic());
            map.put("id", order.getId());
            map.put("createDate", ymdHm(order.getCreateDate()));
            map.put("title", Objects.isNull(topic) ? "" : topic.getTitle());
            map.put("getIcon", Objects.isNull(topic) || StringUtils.isBlank(topic.getIcon()) ? "" : getRealPath(topic.getIcon()));
            map.put("session", order.getUseDate() + " " + order.getStartTime() + "-" + order.getEndTime());
            map.put("ticketType", order.getTicketType());
            map.put("quantity", order.getQuantity());
            map.put("payAmount", StringUtils.isBlank(order.getPayAmount()) ? "" : order.getPayAmount());
            map.put("orderState", order.getOrderState());
            mapList.add(map);
        }
        maps.put("maps", mapList);
        ajaxJson.put("data", maps);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * 订单详情
     *
     * @param req 参数
     * @return 状态
     */
    @RequestMapping("orderInfo")
    public AjaxJson orderInfo(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String orderId = req.getString("orderId");
        if (StringUtils.isBlank(orderId)) {
            ajaxJson.setMsg("订单id不能为空");
            return ajaxJson;
        }
        UserOrder order = userOrderService.get(orderId);
        if (Objects.isNull(order)) {
            ajaxJson.setMsg("该订单不存在");
            return ajaxJson;
        }
        String path = QrCodeUtils.crateB64QRCode(order.getAuthCode(), 310, 310);
        Topic topic = topicService.get(order.getTopic());
        Map<String, Object> map = new HashMap<>();
        map.put("orderId", order.getId());
        map.put("base", path);
        map.put("quantity", order.getQuantity());
        map.put("title", Objects.isNull(order.getTopic()) ? "" : order.getTopic().getTitle());
        map.put("useDate", order.getUseDate());
        map.put("startTime", order.getStartTime());
        map.put("endDate", order.getEndTime());
        map.put("ticketType", order.getTicketType());
        map.put("authCode", order.getAuthCode());
        map.put("uid", order.getU().getId());
        map.put("orderState", order.getOrderState());
        map.put("payAmount", order.getPayAmount());
        map.put("addressDetail", order.getAddressDetail());
        map.put("shopTitle", order.getShopTitle());
        map.put("lon", Objects.isNull(topic) ? "" : topic.getLon());
        map.put("lat", Objects.isNull(topic) ? "" : topic.getLat());
        map.put("qrImage", Objects.isNull(topic) ? "" : getRealPath(topic.getQrImage()));
        map.put("linkman", Objects.isNull(topic) ? "" : topic.getLinkman());
        map.put("wechat", Objects.isNull(topic) ? "" : topic.getWechat());
        map.put("serviceMobile", Objects.isNull(topic) ? "" : topic.getServiceMobile());
        ajaxJson.put("data", map);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * 当日核销记录
     *
     * @param req 参数
     * @return 状态
     */
    @RequestMapping("verifyHistory")
    public AjaxJson verifyHistory(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String uid = req.getString("uid");
        Integer pageNo = req.getInteger("pageNo");
        Integer pageSize = req.getInteger("pageSize");
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        if (Objects.isNull(pageNo) || Objects.isNull(pageSize)) {
            ajaxJson.setMsg("分页参数不能为空");
            return ajaxJson;
        }
        UserOrder userOrder = new UserOrder();
        userOrder.setVerify(member);
        userOrder.setDataScope(" and TO_DAYS(a.create_date) = TO_DAYS(NOW())");
        Page<UserOrder> page = userOrderService.findPage(new Page<>(pageNo, pageSize), userOrder);
        // 查询当日查询到的用户核销的订单
        String count = userOrderService.executeGetSql("SELECT count(1) FROM t_user_order WHERE verify = '" + uid + "' and TO_DAYS(create_date) = TO_DAYS(NOW())").toString();
        Map<String, Object> maps = new HashMap<>();
        maps.put("verifyName", member.getUsername());
        maps.put("countUser", Integer.parseInt(count));
        maps.put("total", page.getLast());
        maps.put("count", page.getCount());
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (UserOrder order : page.getList()) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", order.getId());
            map.put("mobile", order.getMobile());
            map.put("ticketType", order.getTicketType());
            map.put("quantity", order.getQuantity());
            map.put("createDate", hms(order.getCreateDate()));
            mapList.add(map);
        }
        maps.put("dataList", mapList);
        ajaxJson.put("data", maps);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * 核销门票
     *
     * @param req 参数
     * @return 状态
     */
    @RequestMapping("verifyTicket")
    public synchronized AjaxJson verifyTicket(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.setCode(2);
        String uid = req.getString("uid");
        String authCode = req.getString("authCode");
        if (StringUtils.isBlank(authCode)) {
            ajaxJson.setMsg("核销码不能为空");
            return ajaxJson;
        }
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("核销人id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该核销人不存在");
            return ajaxJson;
        }
        UserOrder order = userOrderService.findUniqueByProperty("auth_code", authCode);
        if (Objects.isNull(order)) {
            ajaxJson.setMsg("该核销码无效，请重新核销");
            return ajaxJson;
        }
        if (order.getOrderState().equals(OrderStateEnum.FINISHED.getCode())) {
            ajaxJson.setMsg("该核销码已失效");
            return ajaxJson;
        }
        if (!order.getOrderState().equals(OrderStateEnum.WAIT_USE.getCode())) {
            ajaxJson.setMsg("当前状态不能核销");
            return ajaxJson;
        }
        String ymd = ymd(new Date());
        if (order.getUseDate().compareTo(ymd) > 0) {
            ajaxJson.setMsg("该核销码未到使用时间");
            return ajaxJson;
        }
        if (order.getUseDate().compareTo(ymd) < 0) {
            ajaxJson.setMsg("该核销码已过期");
            return ajaxJson;
        }
        if (order.getUseDate().compareTo(ymd(new Date())) == 0) {
            // 判断当前时间是否到结束时间
            long now = Long.parseLong(hm(new Date()).replace(":", ""));
            long use = Long.parseLong(order.getEndTime().replace(":", ""));
            if (now > use) {
                ajaxJson.setMsg("该核销码已过期");
                return ajaxJson;
            }
        }
        UserOrder userOrder = userOrderService.get(order);
        userOrder.setVerify(member);
        userOrderService.verifyTicket(userOrder);
        Map<String, Object> map = new HashMap<>();
        map.put("topicTitle", order.getTopicTitle());
        map.put("useDate", order.getUseDate());
        map.put("quantity", order.getQuantity());
        map.put("startTime", order.getStartTime());
        map.put("endTime", order.getEndTime());
        map.put("ticketType", order.getTicketType());
        map.put("authCode", order.getAuthCode());
        map.put("mobile", order.getMobile());
        map.put("orderId", order.getId());
        ajaxJson.put("data", map);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }


    /**
     * 订单支付
     *
     * @param req 参数
     * @return 状态
     */
    @RequestMapping("orderPay")
    public synchronized AjaxJson orderPay(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String uid = req.getString("uid");
        String orderId = req.getString("orderId");
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        if (StringUtils.isBlank(orderId)) {
            ajaxJson.setMsg("订单id不能为空");
            return ajaxJson;
        }
        UserOrder order = userOrderService.get(orderId);
        if (Objects.isNull(order)) {
            ajaxJson.setMsg("该订单不存在");
            return ajaxJson;
        }
        if (StringUtils.isBlank(member.getOpenid())) {
            ajaxJson.setMsg("请微信授权登录后，再试");
            return ajaxJson;
        }
        LinkedHashMap<String, Object> info = WxPayUtils.wxPay(member.getOpenid(), "普通商品购买", orderId, order.getPayAmount(), "2", appId, mchNo, notifyUrl, mchSecret);
        ajaxJson.put("data", info);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("加载成功");
        return ajaxJson;
    }

    /**
     * 我的信息
     *
     * @param req 参数
     * @return 状态
     */
    @RequestMapping("my")
    public AjaxJson myInfo(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String uid = req.getString("uid");
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        List<CustomerService> list = customerServiceService.findList(new CustomerService());
        CustomerService customerService = list.get(0);
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isNotBlank(member.getInviteUrl())) {
            map.put("sunCode", getRealPath(member.getInviteUrl()));
        } else {
            String codePath = new WxCodeUtil().getCodePath(member.getInviteCode(), refreshToken(), filePath);
            member.setInviteUrl(codePath);
            memberService.save(member);
            map.put("sunCode", getRealPath(codePath));
        }
        map.put("photo", StringUtils.isBlank(member.getPhoto()) ? "" : getRealPath(member.getPhoto()));
        map.put("mobile", member.getMobile());
        map.put("userType", member.getUserType());
        map.put("nickname", member.getNickname());
        map.put("qrImage", getRealPath(customerService.getQrImage()));
        map.put("linkman", customerService.getLinkman());
        map.put("wechat", customerService.getWechat());
        map.put("serviceMobile", customerService.getServiceMobile());
        ajaxJson.put("data", map);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }


    /**
     * 刷新token
     */
    private String refreshToken() {
        String access = redisTemplate.opsForValue().get("access_token");
        if (StringUtils.isNotBlank(access)) {
            return access;
        }
        String url = "grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
        String loginRet = HttpUtils.sendGet(wxAccToken, url);
        JSONObject json = JsonUtils.toBean(loginRet, JSONObject.class);
        String access_token = json.get("access_token").toString();
        redisTemplate.opsForValue().set(access_token, access_token, 1, TimeUnit.HOURS);
        return access_token;
    }

    /**
     * 取消订单
     *
     * @param req 参数
     * @return 状态
     */
    @RequestMapping("cancelOrder")
    public AjaxJson cancelOrder(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String orderId = req.getString("orderId");
        if (StringUtils.isBlank(orderId)) {
            ajaxJson.setMsg("订单id不能为空");
            return ajaxJson;
        }
        UserOrder userOrder = userOrderService.get(orderId);
        if (Objects.isNull(userOrder)) {
            ajaxJson.setMsg("该订单不存在");
            return ajaxJson;
        }
        userOrder.setOrderState(OrderStateEnum.CANCEL_PAY.getCode());
        userOrderService.save(userOrder);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("订单已取消");
        return ajaxJson;
    }


    /**
     * 按年月份查询是否有票
     *
     * @param req 参数
     * @return 状态
     */
    @RequestMapping("selectStockByMonth")
    public AjaxJson selectStockByMonth(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String topicId = req.getString("topicId");
        String yearMonth = req.getString("yearMonth");
        String ticketTypeId = req.getString("ticketTypeId");
        if (StringUtils.isBlank(topicId)) {
            ajaxJson.setMsg("主题的id不能为空");
            return ajaxJson;
        }
        Topic topic = topicService.get(topicId);
        if (Objects.isNull(topic)) {
            ajaxJson.setMsg("该主题不存在");
            return ajaxJson;
        }
        if (StringUtils.isBlank(yearMonth)) {
            ajaxJson.setMsg("日期不能为空");
            return ajaxJson;
        }
        if (StringUtils.isBlank(ticketTypeId)) {
            ajaxJson.setMsg("主题门票类型的id不能为空");
            return ajaxJson;
        }
        List<Map<String, Object>> mapList = userOrderService.executeSelectSql("SELECT topic_id as topicId, ticket_type_id as ticketTypeId, use_date AS useDate, count(1) AS num FROM t_user_order WHERE topic_id = '" + topicId + "' AND ticket_type_id = '" + ticketTypeId + "' AND DATE_FORMAT( use_date, '%Y-%m' ) = '" + yearMonth + "' GROUP BY use_date");
        List<Map<String, Object>> maps = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(mapList)) {
            // 查询当日是否存在活动
            for (Map<String, Object> map : mapList) {
                Map<String, Object> mapAdd = new HashMap<>();
                Activity activity = new Activity();
                activity.setTopic(topic);
                activity.setTicketTypeId(ticketTypeId);
                activity.setActDate(map.get("useDate").toString());
                List<Activity> list1 = activityService.findList(activity);
                if (CollectionUtils.isNotEmpty(list1)) {
                    Activity activity1 = list1.get(0);
                    if (activity1.getQuantity() - Integer.parseInt(map.get("num").toString()) == 0) {
                        mapAdd.put("date", map.get("useDate"));
                    }
                } else {
                    // 没有活动查询正常价库存
                    TopicTicket topicTicket = new TopicTicket();
                    topicTicket.setTopic(topic);
                    topicTicket.setTicketType(new TicketType(ticketTypeId));
                    List<TopicTicket> list = topicTicketMapper.findList(topicTicket);
                    if (CollectionUtils.isNotEmpty(list)) {
                        TopicTicket topicTicket1 = list.get(0);
                        if (topicTicket1.getStock() - Integer.parseInt(map.get("num").toString()) == 0) {
                            mapAdd.put("date", map.get("useDate"));
                        }
                    }
                }
                if (!mapAdd.isEmpty()) {
                    maps.add(mapAdd);
                }
            }
        }
        ajaxJson.put("data", maps);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }


    /**
     * 查看是否存在活动价
     *
     * @param req 参数
     * @return 状态
     */
    @RequestMapping("selectActPrice")
    public AjaxJson selectActPrice(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String topicId = req.getString("topicId");
        String actDate = req.getString("actDate");
        String ticketTypeId = req.getString("ticketTypeId");
        if (StringUtils.isBlank(topicId)) {
            ajaxJson.setMsg("主题的id不能为空");
            return ajaxJson;
        }
        Topic topic = topicService.get(topicId);
        if (Objects.isNull(topic)) {
            ajaxJson.setMsg("该主题不存在");
            return ajaxJson;
        }
        if (StringUtils.isBlank(actDate)) {
            ajaxJson.setMsg("日期不能为空");
            return ajaxJson;
        }
        if (StringUtils.isBlank(ticketTypeId)) {
            ajaxJson.setMsg("主题门票类型的id不能为空");
            return ajaxJson;
        }
        Activity activity = new Activity();
        activity.setActDate(actDate);
        activity.setTopic(topic);
        activity.setTicketTypeId(ticketTypeId);
        List<Activity> list = activityService.findList(activity);
        Map<String, Object> map = new HashMap<>();
        TopicTicket topicTicket = new TopicTicket();
        topicTicket.setTopic(topic);
        topicTicket.setTicketType(new TicketType(ticketTypeId));
        List<TopicTicket> list1 = topicTicketMapper.findList(topicTicket);
        if (CollectionUtils.isNotEmpty(list)) {
            Activity activity1 = list.get(0);
            map.put("price", activity1.getPrice());
        } else {
            if (CollectionUtils.isNotEmpty(list1)) {
                TopicTicket topicTicket1 = list1.get(0);
                map.put("price", topicTicket1.getPrice());
            }
        }
        ajaxJson.put("data", map);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }


    /**
     * @param req 参数
     * @return 状态
     */
    @RequestMapping("test")
    public AjaxJson test(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String uid = req.getString("uid");
        Integer pageNo = req.getInteger("pageNo");
        Integer pageSize = req.getInteger("pageSize");
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        if (Objects.isNull(pageNo) || Objects.isNull(pageSize)) {
            ajaxJson.setMsg("分页参数不能为空");
            return ajaxJson;
        }
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }
}